<?php 


class Wechat{

    static $appid;
    static $appsecret;
    static $token;
    static $cpm;
    static $contentType=['image/gif'=>'gif','image/jpeg'=>'jpg','image/pjpeg'=>'jpg','image/png'=>'png','image/x-png'=>'png','  audio/mpeg'=>'mp3','audio/amr'=>'amr','video/mp4'=>'mp4'];
    static $customer_group=[
                            ['id'=>'90086','content'=>'1、售前','str'=>'front'],
                            ['id'=>'90087','content'=>'2、售后','str'=>'after'],
                            ['id'=>'90088','content'=>'3、钱客多技术','str'=>'it'],
                            ['id'=>'90089','content'=>'4、其他','str'=>'other'],
                           ];
    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";

    static $menu_create_url = 'https://api.weixin.qq.com/cgi-bin/menu/create?';
    //客服
    static $customer_list = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?';
    static $customer_online_list = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?';
    static $customer_add = 'https://api.weixin.qq.com/customservice/kfaccount/add?';
    static $customer_update = 'https://api.weixin.qq.com/customservice/kfaccount/update?';
    static $customer_del = 'https://api.weixin.qq.com/customservice/kfaccount/del?';
    static $customer_uploadheadimg = 'http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?';
    static $customer_inviteworker = 'https://api.weixin.qq.com/customservice/kfaccount/inviteworker?';
    static $customer_typing = 'https://api.weixin.qq.com/cgi-bin/message/custom/typing?';
    static $customer_send = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?';
    //会话
    static $session_create = 'https://api.weixin.qq.com/customservice/kfsession/create?';
    static $session_close = 'https: //api.weixin.qq.com/customservice/kfsession/close?';
    static $session_get  = 'https://api.weixin.qq.com/customservice/kfsession/getsession?';
    //获取用户信息
    static $user_info = 'https://api.weixin.qq.com/cgi-bin/user/info?';
    //素材
    static $upload = 'https://api.weixin.qq.com/cgi-bin/media/upload?';
    static $https_get = 'https://api.weixin.qq.com/cgi-bin/media/get?';
    static $http_get = 'http://api.weixin.qq.com/cgi-bin/media/get?';

    public static function setConfig($appid, $appsecret, $token, $cpm)
    {
        self::$appid=$appid;
        self::$appsecret=$appsecret;
        self::$token = $token;
        self::$cpm = $cpm;
    }

    public static function getConfig()
    {
        return ['appid' => self::$appid, 'appsecret' => self::$appsecret, 'token' => self::$token];
    }
    //消息回复
    public static function responseMsg($msgType='',$content='')
    {
        $postArr = file_get_contents('php://input');
        if(empty($postArr)){
            echo '';
        }else{
            $postObj = simplexml_load_string($postArr);
            if(strtolower($postObj->MsgType) == 'event'){
                if(strtolower($postObj->Event) == 'subscribe'){
                    $toUser = $postObj->FromUserName;
                    $fromUser = $postObj->ToUserName;
                    $EventKey = $postObj->EventKey;
                    //参数前缀qrscene_
                    $param=str_replace('qrscene_','',$EventKey);
                    $keyword=trim($postObj->Content);
                    
                    $time = time();
                    if(!$msgType)$msgType = 'text';
                    if (!$content) $content = '欢迎关注西电耐斯公众号！';
                    $template = "<xml>
                                    <ToUserName><![CDATA[%s]]></ToUserName>
                                    <FromUserName><![CDATA[%s]]></FromUserName>
                                    <CreateTime>%s</CreateTime>
                                    <MsgType><![CDATA[%s]]></MsgType>
                                    <Content><![CDATA[%s]]></Content>
                                </xml>";
                    if(!empty($keyword)){
                        $info = sprintf($template,$toUser,$fromUser,$time,$msgType,$content);
                        echo $info;
                    }else{
                        echo 'Input something...';
                    }
                }
            }
        }
    }
    //验证字段
    public static function checkSignature()
    {
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];

        $tmpArr = array(self::$token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }
        return false;
    }
    //生成自定义菜单
    public static function createMenu($data)
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$menu_create_url.'access_token='.$ACCESS_TOKEN;
        $menu = array();
        $i=0;
        foreach ($data as $item){
            $menu['button'][$i]['name'] = $item['name'][0];
            if($item['sub_button']){
                $j=0; 
                foreach ($item['sub_button'] as $sub){
                    $menu['button'][$i]['sub_button'][$j]['type'] = 'view';
                    $menu['button'][$i]['sub_button'][$j]['name'] = $sub[0];
                    $menu['button'][$i]['sub_button'][$j]['url'] = $sub[1];
                    $j++;
                }
            }else{
                $menu['button'][$i]['type'] = 'view';
                $menu['button'][$i]['url'] = $item['name'][1];
            }
            $i++;
        }

        $data = self::xjson_encode($menu);
        $data = str_replace('\/','/',$data);
        $result = self::http_post_data($url,$data);
        // var_dump($result);
        return json_decode($result[1],true);
    }

    public static function createMenus($data)
    {
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = self::$menu_create_url . 'access_token=' . $ACCESS_TOKEN;

        $result = self::http_post_data($url, $data);

        return json_decode($result[1], true);
    }

    public static function delMenu()
    {
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $ACCESS_TOKEN;
        return file_get_contents($url);
    }

    public static function getMenu()
    {
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $ACCESS_TOKEN;
        return file_get_contents($url);
    }

    public static function getService()
    {
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" . $ACCESS_TOKEN;
        return file_get_contents($url);
    }

    public static function imageMaterial($page)
    {
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" . $ACCESS_TOKEN;
        {
          $post["type"] = 'image';
          $post["offset"] = ($page - 1) * 20;
          $post["count"] = 20;
        }
        return send_curl($url, json_encode($post));
    }

    /**
     *  发送客服图文消息
     */
    public static function sendServiceMessage($post){
        $ACCESS_TOKEN = self::getToken();
        if (!$ACCESS_TOKEN) return false;
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $ACCESS_TOKEN;
        $post = is_array($post) ? json_encode($post, JSON_UNESCAPED_UNICODE) : $post;
        return send_curl($url, $post);
    }
    /**
     * 上传素材
     */
    public static function upload($type,$filepath)
    {
    	if(!file_exists($filepath)){
    		return false;
    	}
    	$ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$upload.'access_token='.$ACCESS_TOKEN.'&type='.$type;
        $result =self::http_post_data($url,['media'=>new \CURLFile($filepath)]);
        $oo = json_decode($result[1]);
        if (empty($oo) || !property_exists($oo, 'media_id')){
            return false;
        }
        return $oo->media_id;
    }
    public static function newget($msg_type,$media_id)
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$https_get."access_token=".$ACCESS_TOKEN."&media_id=".$media_id;

        $arr=self::downloadWeixinFile($url);
        file_put_contents('./header.log',json_encode($arr['header']),FILE_APPEND);
        $content_type_arr=self::$contentType;
        $content_type=$arr['header']['content_type'];
        if(array_key_exists($content_type,$content_type_arr)){
            $type=$content_type_arr[$content_type];

            $file_name=date('YmdHis').rand(1000,9999).'.'.$type;

            if (!file_exists("./static/upload/wxkf/".date('Ymd'))) {
                mkdir("./static/upload/wxkf/".date('Ymd'), 0777, true);
            }
            $targetName = './static/upload/wxkf/'.date('Ymd').'/'.$file_name;

            $local_file = fopen($targetName, 'w');
            if (false !== $local_file){
                if (false !== fwrite($local_file, $arr['body'])) {
                    fclose($local_file);
                }
            }
        }else{
            file_put_contents('./contenttype.log',$content_type,FILE_APPEND);
        }
    }
    public  static   function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
        return $imageAll;
    }
    public static function downFile($url, $savePath = './uploads')
    {

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_HEADER, TRUE);  //需要response header
      curl_setopt($ch, CURLOPT_NOBODY, FALSE);  //需要response body
      $response = curl_exec($ch);
      //分离header与body
      $header = '';
      $body = '';
      if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); //头信息size
        $header = substr($response, 0, $headerSize);
        $body = substr($response, $headerSize);
      }
      curl_close($ch);
      //文件名
      $arr = array();
      if (preg_match('/filename="(.*?)"/', $header, $arr)) {
        $file = date('Ym') . '/' . $arr[1];
        $fullName = rtrim($savePath, '/') . '/' . $file;
        //创建目录并设置权限
        $basePath = dirname($fullName);
        if (!file_exists($basePath)) {
          @mkdir($basePath, 0777, true);
          @chmod($basePath, 0777);
        }
        if (file_put_contents($fullName, $body)) {
          return $file;
        }
      }
      return false;
    }
    /**
     * 获取素材
     */
    public static function get($type,$media_id)
    {
    	$ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url=self::$https_get;
        $postfix='';
        switch ($type) {
        	case 'thumb':
        	case 'image':
        		$postfix='.jpg';
        		break;
        	case 'shortvideo':
        	case 'video':
        		$url=self::$http_get;
        		$postfix='.mp4';
        		break;
        	case 'voice':
        		$postfix='.mp3';
        		break;
        }
        if(empty($postfix)){
        	return false;
        }
    	$url = $url."access_token=".$ACCESS_TOKEN."&media_id=".$media_id;
        if (!file_exists("./static/upload/wxkf/".date('Ymd'))) {
            mkdir("./static/upload/wxkf/".date('Ymd'), 0777, true);
        }
        $file_name=date('YmdHis').rand(1000,9999).$postfix;
        $targetName = './static/upload/wxkf/'.date('Ymd').'/'.$file_name;

        $ch = curl_init($url); // 初始化
        $fp = fopen($targetName, 'wb'); // 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置，值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return $targetName;
    }
    /**
     * 获取用户信息
     * @return [type] [description]
     */
    public static function getUserInfo($openid)
    {
    	$cache_key = $openid.'_' . self::$cpm;
        $user_info = cache($cache_key);
        if(empty($user_info)){
        	$ACCESS_TOKEN = self::getToken();
        	if (!$ACCESS_TOKEN) return false;
        	$url = self::$user_info."access_token=" . $ACCESS_TOKEN."&openid=".$openid."&lang=zh_CN";
        	$user_info=file_get_contents($url);
        	$user_info=json_decode($user_info,true);
        	if(array_key_exists('openid',$user_info)){
        		cache($cache_key, $user_info, 30*24*3600);
        	}
        }
        return $user_info;
    }
    /**
     * 获取所有客服列表
     */
    public static function getCustomerList()
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_list.'access_token='.$ACCESS_TOKEN;
        $result =file_get_contents($url);
        $result = json_decode($result,true);
        if(!array_key_exists('kf_list', $result)){
            return false;
        }
        return $result['kf_list'];
    }
    /**
     * 获取在线客服列表
     */
    public static function getCustomerOnlineList()
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_online_list.'access_token='.$ACCESS_TOKEN;
        $result =file_get_contents($url);

        $result = json_decode($result,true);
        if(!array_key_exists('kf_online_list', $result)){
            return false;
        }
        return $result['kf_online_list'];
    }
    /**
     * 添加客服
     * @param string $kf_account  客服账号（前缀@公众号微信号）
     * @param string $nickname 客服昵称
     */
    public static function addCustomer($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_add.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 绑定客服
     * @param  string $kf_account 客服账号
     * @param  string $invite_wx  绑定的微信号
     */
    public static function inviteworkerCustomer($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_inviteworker.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 修改客服信息
     * @param string $kf_account 客服账号
     * @param string $nickname 客服昵称
     */
    public static function updateCustomer($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_update.'access_token='.$ACCESS_TOKEN;
        $result = self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 删除客服
     * @param string $kf_account 客服账号
     */
    public static function delCustomer($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_del.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 客服发送消息
     * @param string $touse openid
     * @param string $msgtype 消息类型
     * @param string $content 消息内容
     * @param string $kf_account 客服账号
     */
    public static function sendCustomerMsg($toUser,$msgtype,$content,$kf_account='')
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_send.'access_token='.$ACCESS_TOKEN;
        $data=[];
        switch ($msgtype) {
            case 'text':
                $data['touser']=$toUser;
                $data['msgtype']='text';
                $data['text']=['content'=>$content];
                break;
            case 'msgmenu'://菜单
                $data['touser']=$toUser;
                $data['msgtype']='msgmenu';
                $data['msgmenu']=$content;
                break;
            case 'image'://图片
                $data['touser']=$toUser;
                $data['msgtype']='image';
                $data['image']=$content;
                break;
            case 'voice'://语音
                $data['touser']=$toUser;
                $data['msgtype']='voice';
                $data['voice']=$content;
                break;
            case 'video'://视频
                $data['touser']=$toUser;
                $data['msgtype']='video';
                $data['video']=$content;
                break;
            case 'music'://音乐
                $data['touser']=$toUser;
                $data['msgtype']='music';
                $data['music']=$content;
                break;
            case 'news'://图文
                $data['touser']=$toUser;
                $data['msgtype']='news';
                $data['news']=['articles'=>$content];
                break;
            case 'mpnews'://图文
                $data['touser']=$toUser;
                $data['msgtype']='mpnews';
                $data['mpnews']=$content;
                break;
            default:
                # code...
                break;
        }
        if(empty($data)) return false;
        if(!empty($kf_account)) $data['customservice']=['kf_account'=>$kf_account];
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 客服输入状态
     * @param string $touser（用户openid）
     * @param string $command Typing
     */
    public static function typingCustomer($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$customer_typing.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 在在线客服列表随机选一个 创建会话
     * @param  string $kf_account 客服账号
     * @param  string $openid     用户openid
     */
    public static function createSession($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$session_create.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 在在线客服列表随机选一个 创建会话
     * @param  string $kf_account 客服账号
     * @param  string $openid     用户openid
     */
    public static function closeSession($data)
    {
        if(empty($data)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$session_close.'access_token='.$ACCESS_TOKEN;
        $result =self::http_post_data($url,self::xjson_encode($data));
        $oo = json_decode($result[1]);
        if (empty($oo) || $oo->errcode!=0){
            return false;
        }
        return true;
    }
    /**
     * 获取用户的会话状态
     * @param string $openid 用户openid
     */
    public static function getSession($openid)
    {
        if(empty($openid)) return false;
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$session_get.'access_token='.$ACCESS_TOKEN.'&openid='.$openid;
        $result =file_get_contents($url);

        $result = json_decode($result,true);
        return $result;
    }
    //生成二维码  并保存本地服务器
    public static function getEwm($fqid,$type = 1,$filestring)
    {
        $ACCESS_TOKEN = self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::getQrcodeurl($ACCESS_TOKEN,$fqid,$type);
        // save_log('测试保存的路径'.$url.'fid'.$fqid);
        return self::DownLoadQr($url,$filestring);
    }
    //生成二维码 返回链接
    public static function getQrcodeurl($fqid,$type = 1)
    {
        $ACCESS_TOKEN=self::getToken();
        if(!$ACCESS_TOKEN) return false;
        $url = self::$qrcode_url.'access_token='.$ACCESS_TOKEN;
        if($type == 1){//生成永久二维码
            if(is_numeric($fqid)){//场景id
                $qrcode= '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$fqid.'}}}';
            }else{
                $qrcode= '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$fqid.'"}}}';
            }
        }else{//生成临时二维码
            if(is_numeric($fqid)){//场景id
                $qrcode = '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$fqid.'}}}';
            }else{
                $qrcode = '{"expire_seconds": 2592000, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$fqid.'"}}}';
            }
        }
        // var_dump($qrcode);
        $result =self::http_post_data($url,$qrcode);
        $oo = json_decode($result[1]);
        if (empty($oo->ticket)){
            return false;
        }
        if(!$oo->ticket){
            return false;
        }
        $url = self::$qrcode_get_url.'ticket='.$oo->ticket.'';
        return $url;
    }
    //下载二维码到服务器
    public static function DownLoadQr($url,$filestring)
    {
        if($url == ""){
            return false;
        }
        $filename = $filestring.'.jpg';
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
        $size=strlen($img);
        $fp2=fopen('/qrcode/'.$filename,"a");
        if(fwrite($fp2,$img) === false){
            // $this->ErrorLogger('dolwload image falied. Error Info: 无法写入图片');
            return false;
        }
        fclose($fp2);
        return '/qrcode/'.$filename;
    }
    //获取token
    public static function getToken()
    {
        // if (defined('SANDBOX') && SANDBOX) self::$cpm = 7;
        $cache_key = 'wx_token_' . self::$cpm;
        $ACCESS_TOKEN = cache($cache_key);
        if (empty($ACCESS_TOKEN)) {
            $url = self::$token_url . "appid=" . self::$appid . "&secret=" . self::$appsecret;
            $ACCESS_TOKEN = send_curl($url);
            $ACCESS_TOKEN = json_decode($ACCESS_TOKEN);
            if (!property_exists($ACCESS_TOKEN, 'access_token')) {
                return false;
            }
            $ACCESS_TOKEN = $ACCESS_TOKEN->access_token;
            cache($cache_key, $ACCESS_TOKEN, 7000);
            cache('wx_token_expire_' . self::$cpm, time()+7000, 7000);
        }
        return $ACCESS_TOKEN;
    }
 
    public static function http_post_data($url, $data_string)
    {
 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        if(is_string($data_string)){
	        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	                'Content-Type: application/json; charset=utf-8',
	                'Content-Length: ' . strlen($data_string))
	        );
	    }
        ob_start();
        curl_exec($ch);
        if (curl_errno($ch)) {
            self::ErrorLogger('curl falied. Error Info: '.curl_error($ch));
        }
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }
    //json格式
    public static function xjson_encode($data)
    {
        if(version_compare(PHP_VERSION,'5.4.0','<')){
            $str = json_encode($data);
            $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i",function($matchs){
                return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
            },$str);
            return $str;
        }
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    //错误日志
    private static function ErrorLogger($errMsg){
        $logger = fopen('D:/wwwroot/xxdd/public/static/log.txt', 'a+');
        fwrite($logger, date('Y-m-d H:i:s')." Error Info : ".$errMsg."\r\n");
        fclose($logger);
    }
 
}